CloudflareR2Cloudflare R2 Java连接工具类
nodaoliCloudflare R2是一个基于Amazon S3 API的云存储服务,它允许您存储和检索对象,如图像、视频、音频和文档。
Cloudflare R2使用Amazon S3 API,因此您可以使用任何Amazon S3 SDK或工具来与R2进行交互。
引入Maven依赖
1 2 3 4
| <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>s3</artifactId> <version>2.27.13</version>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import java.io.IOException; import java.net.URI; import java.nio.file.Paths;
@Slf4j @Component public class R2Utils {
private static String accessKeyId = "<your-access-key-id>"; private static String secretAccessKey = "<your-secret-access-key>"; private static String endpoint = "https://<your-access-id>.r2.cloudflarestorage.com"; private static String bucketName = "<your-bucket-name>";
public static String uploadFile(MultipartFile file) throws IOException { S3Client s3 = S3Client.builder() .endpointOverride(URI.create(endpoint)) .region(Region.US_EAST_1) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKeyId, secretAccessKey))) .build();
PutObjectRequest putObjectRequest = PutObjectRequest.builder() .bucket(bucketName) .key(file.getOriginalFilename()) .build();
PutObjectResponse response = s3.putObject( putObjectRequest, software.amazon.awssdk.core.sync.RequestBody.fromBytes(file.getBytes()) ); log.info("File uploaded successfully: {}" , response.eTag());
s3.close(); String url = "https://<your-domain>/"+file.getOriginalFilename(); return url; } }
|